package com.kds.smarthome.controller;

import com.kds.smarthome.common.AjaxResponse;
import com.kds.smarthome.entity.QuartzJob;
import com.kds.smarthome.service.QuartzJobLogService;
import com.kds.smarthome.service.QuartzJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Quartz定时任务控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/quartz/job")
public class QuartzJobController {

    @Autowired
    private QuartzJobService quartzJobService;

    @Autowired
    private QuartzJobLogService quartzJobLogService;

    /**
     * 获取所有任务
     */
    @GetMapping
    public AjaxResponse<List<QuartzJob>> getAllJobs() {
        try {
            List<QuartzJob> jobs = quartzJobService.getAllJobs();
            return AjaxResponse.success(jobs);
        } catch (Exception e) {
            log.error("获取所有任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/{jobId}")
    public AjaxResponse<QuartzJob> getJob(@PathVariable String jobId) {
        try {
            QuartzJob job = quartzJobService.getJobById(jobId);
            if (job == null) {
                return AjaxResponse.error("任务不存在");
            }
            return AjaxResponse.success(job);
        } catch (Exception e) {
            log.error("获取任务详情失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 添加任务
     */
    @PostMapping
    public AjaxResponse<?> addJob(@RequestBody QuartzJob job) {
        try {
            // 检查CRON表达式
            if (!quartzJobService.checkCronExpression(job.getCronExpression())) {
                return AjaxResponse.error("CRON表达式无效: " + job.getCronExpression());
            }

            quartzJobService.addJob(job);
            return AjaxResponse.success("添加任务成功");
        } catch (Exception e) {
            log.error("添加任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 更新任务
     */
    @PutMapping("/{jobId}")
    public AjaxResponse<?> updateJob(@PathVariable String jobId, @RequestBody QuartzJob job) {
        try {
            job.setJobId(jobId);

            // 检查CRON表达式
            if (job.getCronExpression() != null && !quartzJobService.checkCronExpression(job.getCronExpression())) {
                return AjaxResponse.error("CRON表达式无效: " + job.getCronExpression());
            }

            quartzJobService.updateJob(job);
            return AjaxResponse.success("更新任务成功");
        } catch (Exception e) {
            log.error("更新任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{jobId}")
    public AjaxResponse<?> deleteJob(@PathVariable String jobId) {
        try {
            quartzJobService.deleteJob(jobId);
            return AjaxResponse.success("删除任务成功");
        } catch (Exception e) {
            log.error("删除任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 暂停任务
     */
    @PostMapping("/{jobId}/pause")
    public AjaxResponse<?> pauseJob(@PathVariable String jobId) {
        try {
            quartzJobService.pauseJob(jobId);
            return AjaxResponse.success("暂停任务成功");
        } catch (Exception e) {
            log.error("暂停任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 恢复任务
     */
    @PostMapping("/{jobId}/resume")
    public AjaxResponse<?> resumeJob(@PathVariable String jobId) {
        try {
            quartzJobService.resumeJob(jobId);
            return AjaxResponse.success("恢复任务成功");
        } catch (Exception e) {
            log.error("恢复任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 立即执行任务
     */
    @PostMapping("/{jobId}/run")
    public AjaxResponse<?> runJob(@PathVariable String jobId) {
        try {
            quartzJobService.runJobNow(jobId);
            return AjaxResponse.success("触发任务成功");
        } catch (Exception e) {
            log.error("触发任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 获取CRON表达式的下次执行时间
     */
    @GetMapping("/cron/next")
    public AjaxResponse<List<String>> getNextExecuteTime(@RequestParam String cronExpression,
                                                       @RequestParam(required = false) Integer count) {
        try {
            // 检查CRON表达式
            if (!quartzJobService.checkCronExpression(cronExpression)) {
                return AjaxResponse.error("CRON表达式无效: " + cronExpression);
            }

            List<String> nextTimes = quartzJobService.getNextExecuteTimeList(cronExpression, count);
            return AjaxResponse.success(nextTimes);
        } catch (Exception e) {
            log.error("获取下次执行时间失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 获取正在运行的任务
     */
    @GetMapping("/running")
    public AjaxResponse<List<QuartzJob>> getRunningJobs() {
        try {
            List<QuartzJob> jobs = quartzJobService.getRunningJobs();
            return AjaxResponse.success(jobs);
        } catch (Exception e) {
            log.error("获取正在运行的任务失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 获取任务日志（分页查询）
     */
    @GetMapping("/{jobId}/logs")
    public AjaxResponse<Map<String, Object>> getJobLogs(
            @PathVariable String jobId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = quartzJobLogService.getJobLogsByPage(
                    jobId, null, null, status, startTime, endTime, pageNum, pageSize);
            return AjaxResponse.success(result);
        } catch (Exception e) {
            log.error("获取任务日志失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 查询任务日志（分页查询）
     */
    @GetMapping("/logs")
    public AjaxResponse<Map<String, Object>> getJobLogs(
            @RequestParam(required = false) String jobName,
            @RequestParam(required = false) String jobGroup,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = quartzJobLogService.getJobLogsByPage(
                    null, jobName, jobGroup, status, startTime, endTime, pageNum, pageSize);
            return AjaxResponse.success(result);
        } catch (Exception e) {
            log.error("查询任务日志失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 清空指定日期之前的日志
     */
    @DeleteMapping("/logs/clean")
    public AjaxResponse<?> cleanJobLogs(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beforeDate) {
        try {
            quartzJobLogService.cleanJobLogs(beforeDate);
            return AjaxResponse.success("清空日志成功");
        } catch (Exception e) {
            log.error("清空日志失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }

    /**
     * 验证CRON表达式
     */
    @PostMapping("/cron/validate")
    public AjaxResponse<?> validateCronExpression(@RequestBody Map<String, String> params) {
        try {
            String cronExpression = params.get("cronExpression");
            if (cronExpression == null) {
                return AjaxResponse.error("CRON表达式不能为空");
            }

            boolean isValid = quartzJobService.checkCronExpression(cronExpression);
            Map<String, Object> result = new HashMap<>();
            result.put("isValid", isValid);

            if (isValid) {
                List<String> nextTimes = quartzJobService.getNextExecuteTimeList(cronExpression, 5);
                result.put("nextExecuteTimes", nextTimes);
            }

            return AjaxResponse.success(result);
        } catch (Exception e) {
            log.error("验证CRON表达式失败", e);
            return AjaxResponse.error(e.getMessage());
        }
    }
}
